/**
 * 
 */
package org.chungyan5.multiplenestingtagging.mobile;

import org.chungyan5.multiplenestingtagging.DbConn;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author yan
 *
 */
public class TagAttachItems extends Activity {
	
	private ListView listViewStuffs;
	private Cursor itemsCursor = null;
	private Cursor selTagsCursor = null;
	private Cursor relTagsCursor = null;
	private SimpleCursorAdapter adapterStuff;
	private long tagId;

    public void onCreate(Bundle savedInstanceState) {
    	
	    // show this Activity ====================================================
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.tag_attach_items);
	    
	    // get which Tag ====================================================
	    Bundle bundle = this.getIntent().getExtras();
	    tagId = bundle.getLong("id");
	    
	    // background to get back all Tags fr. Db =================================
        new GetTagsTask().execute();
        
    }

	private class GetTagsTask extends AsyncTask<String, Void, String> {

		protected void onPreExecute() {
		}

		protected String doInBackground(final String... args) {
			Uri uriStuffs;
			
			// query attached item(s) ==============
			uriStuffs = Uri.withAppendedPath(MNTContentProvider.CONTENT_URI, MNTContentProvider.TAG_ATTACHED_ITEMS_PATH);
			itemsCursor = managedQuery(uriStuffs, null, Long.toString(tagId), null, null);
			
			// query selected Tag(s) ==============
			uriStuffs = Uri.withAppendedPath(MNTContentProvider.CONTENT_URI, MNTContentProvider.TAG_ATTACHED_SEL_TAGS_PATH);
			selTagsCursor = managedQuery(uriStuffs, null, null, null, null);
			
			// query related Tag(s) ==============
			uriStuffs = Uri.withAppendedPath(MNTContentProvider.CONTENT_URI, MNTContentProvider.TAG_ATTACHED_REL_TAGS_PATH);
			relTagsCursor = managedQuery(uriStuffs, null, null, null, null);
			
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final String result) {
			startManagingCursor(itemsCursor);

			// handle the selected Tag(s) ======================================
			listViewStuffs = (ListView) findViewById(R.id.ListViewSelTags);
			adapterStuff = new SimpleCursorAdapter(TagAttachItems.this
					, R.layout.single_stuff_in_id_name, selTagsCursor
					, new String[] { DbConn.TABLE_TAG_COL_TAG_PTR, DbConn.TABLE_TAG_COL_TAG_NAME }
					, new int[] { R.id.listStuffId, R.id.listStuffName });
			listViewStuffs.setAdapter(adapterStuff);
			listViewStuffs.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					
					// remove the memory set for selected Tag(s) ===================
					int removeCnt = selTagsCursor.getCount() - position + 1;		// +1 means remove one more, then it will refresh screen to add back 
					getContentResolver().delete(Uri.withAppendedPath(MNTContentProvider.CONTENT_URI, 
							MNTContentProvider.TAG_ATTACHED_SEL_TAGS_PATH), String.valueOf(removeCnt), null);

					// refresh the screen ===========================
					if (--position<0) position = 0;			// point back to previous one
					selTagsCursor.moveToPosition(position);
					tagId = selTagsCursor.getLong(selTagsCursor.getColumnIndex(DbConn.TABLE_TAG_COL_TAG_PTR));
					new GetTagsTask().execute();		
				}
				
			});

			// handle the Related Tag(s) =======================================
			listViewStuffs = (ListView) findViewById(R.id.ListViewRelTags);
			adapterStuff = new SimpleCursorAdapter(TagAttachItems.this
					, R.layout.single_stuff_in_id_name, relTagsCursor
					, new String[] { DbConn.TABLE_TAG_COL_TAG_PTR, DbConn.TABLE_TAG_COL_TAG_NAME }
					, new int[] { R.id.listStuffId, R.id.listStuffName });
			listViewStuffs.setAdapter(adapterStuff);
			listViewStuffs.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					relTagsCursor.moveToPosition(position);
//					Context context = getApplicationContext();
//					Toast toast = Toast.makeText(context, "clicking for Related at " + relTagsCursor.getLong(relTagsCursor.getColumnIndex(DbConn.TABLE_TAG_COL_TAG_PTR)), Toast.LENGTH_SHORT);
//					toast.show();
					tagId = relTagsCursor.getLong(relTagsCursor.getColumnIndex(DbConn.TABLE_TAG_COL_TAG_PTR));
					new GetTagsTask().execute();		// refresh the screen
				}
				
			});

			// handle the attached Item(s) =====================================
			listViewStuffs = (ListView) findViewById(R.id.ListViewAttachedItems);
			adapterStuff = new SimpleCursorAdapter(TagAttachItems.this
					, R.layout.single_stuff_in_id_name, itemsCursor
					, new String[] { DbConn.TABLE_TAG_ITEM_REL_COL_ITEM_PTRS, DbConn.TABLE_ITEM_COL_ITEM_NAME }
					, new int[] { R.id.listStuffId, R.id.listStuffName });
			listViewStuffs.setAdapter(adapterStuff);
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
//		Log.d("yan", "TagAttachItems destroy");
		getContentResolver().delete(Uri.withAppendedPath(MNTContentProvider.CONTENT_URI, MNTContentProvider.TAG_ATTACHED_SEL_TAGS_PATH), null, null);
		getContentResolver().delete(Uri.withAppendedPath(MNTContentProvider.CONTENT_URI, MNTContentProvider.TAG_ATTACHED_REL_TAGS_PATH), null, null);
	}

}
